<template>
  <!-- 添加用户对话框 -->
  <el-dialog 
    v-model="visible" 
    title="添加用户" 
    width="500px" 
    @close="close" 
    destroy-on-close
    :close-on-click-modal="false"
    class="user-add-dialog"
  >
    <el-form 
      ref="userAddForm" 
      :model="userAdd" 
      :rules="rules" 
      label-position="top"
      class="user-form"
      :validate-on-rule-change="false"
    >
      <el-form-item label="用户名" prop="userCode">
        <el-input 
          v-model="userAdd.userCode" 
          placeholder="请输入用户名"
          prefix-icon="User"
          :maxlength="20"
          show-word-limit
          clearable
        />
      </el-form-item>
      <el-form-item label="昵称" prop="userName">
        <el-input 
          v-model="userAdd.userName" 
          placeholder="请输入昵称"
          prefix-icon="UserFilled"
          :maxlength="20"
          show-word-limit
          clearable
        />
      </el-form-item>
      <el-form-item label="密码" prop="userPwd">
        <el-input 
          type="password" 
          v-model="userAdd.userPwd" 
          placeholder="请输入密码"
          prefix-icon="Lock"
          show-password
          :maxlength="20"
        />
        <div class="password-strength" v-if="userAdd.userPwd">
          <div class="strength-label">密码强度：</div>
          <div class="strength-indicators">
            <div 
              class="indicator" 
              :class="{ active: passwordStrength >= 1 }"
              :style="{ backgroundColor: strengthColor }"
            ></div>
            <div 
              class="indicator" 
              :class="{ active: passwordStrength >= 2 }"
              :style="{ backgroundColor: strengthColor }"
            ></div>
            <div 
              class="indicator" 
              :class="{ active: passwordStrength >= 3 }"
              :style="{ backgroundColor: strengthColor }"
            ></div>
          </div>
          <span class="strength-text" :style="{ color: strengthColor }">
            {{ strengthText }}
          </span>
        </div>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input 
          type="password" 
          v-model="userAdd.confirmPassword" 
          placeholder="请再次输入密码"
          prefix-icon="Lock"
          show-password
          :maxlength="20"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button 
          type="primary" 
          @click="addUser" 
          :loading="loading"
        >
          {{ loading ? '添加中...' : '确定' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { post, tip } from "@/common";
import { User, UserFilled, Lock } from '@element-plus/icons-vue'

const visible = ref(false);
const loading = ref(false);

// 添加用户对象
const userAdd = reactive({
  userCode: '',
  userName: '',
  userPwd: '',
  confirmPassword: ''
});

// 密码强度计算
const passwordStrength = computed(() => {
  const pwd = userAdd.userPwd;
  if (!pwd) return 0;
  
  let strength = 0;
  // 长度检查
  if (pwd.length >= 8) strength++;
  // 包含数字和字母
  if (/[a-zA-Z]/.test(pwd) && /[0-9]/.test(pwd)) strength++;
  // 包含特殊字符
  if (/[!@#$%^&*(),.?":{}|<>]/.test(pwd)) strength++;
  
  return strength;
});

const strengthColor = computed(() => {
  switch (passwordStrength.value) {
    case 1: return '#ff4949';
    case 2: return '#e6a23c';
    case 3: return '#67c23a';
    default: return '#909399';
  }
});

const strengthText = computed(() => {
  switch (passwordStrength.value) {
    case 1: return '弱';
    case 2: return '中';
    case 3: return '强';
    default: return '无';
  }
});

// 表单验证规则
const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'));
  } else if (value.length < 6 || value.length > 20) {
    callback(new Error('密码长度为6-20位'));
  } else {
    if (userAdd.confirmPassword !== '') {
      userAddForm.value?.validateField('confirmPassword');
    }
    callback();
  }
};

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'));
  } else if (value !== userAdd.userPwd) {
    callback(new Error('两次输入密码不一致'));
  } else {
    callback();
  }
};

const rules = reactive({
  userCode: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度为3-20位', trigger: 'blur' }
  ],
  userName: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度为2-20位', trigger: 'blur' }
  ],
  userPwd: [
    { validator: validatePass, trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: validatePass2, trigger: 'blur' }
  ]
});

// 重置表单
const resetForm = () => {
  Object.assign(userAdd, {
    userCode: '',
    userName: '',
    userPwd: '',
    confirmPassword: ''
  });
  userAddForm.value?.resetFields();
};

// 关闭对话框
const close = () => {
  resetForm();
  visible.value = false;
};

// 打开对话框
const open = () => {
  visible.value = true;
};

const userAddForm = ref();
const emit = defineEmits(["ok"]);

// 添加用户
const addUser = async () => {
  await userAddForm.value?.validate();
  
  loading.value = true;
  try {
    const result = await post('/user/addUser', userAdd);
    emit('ok');
    tip.success(result.message);
    close();
  } catch (error) {
    console.error('Failed to add user:', error);
  } finally {
    loading.value = false;
  }
};

defineExpose({ open });
</script>

<style scoped>
.user-add-dialog {
  --el-dialog-padding-primary: 20px;
}

.user-form {
  padding: 0 20px;
}

:deep(.el-form-item__label) {
  padding-bottom: 8px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px var(--el-color-primary) inset;
}

.password-strength {
  margin-top: 8px;
  display: flex;
  align-items: center;
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.strength-label {
  margin-right: 8px;
}

.strength-indicators {
  display: flex;
  gap: 4px;
  margin-right: 8px;
}

.indicator {
  width: 24px;
  height: 4px;
  background-color: #dcdfe6;
  border-radius: 2px;
  transition: all 0.3s ease;
}

.indicator.active {
  opacity: 1;
}

.strength-text {
  font-weight: 500;
}

.dialog-footer {
  padding: 20px 0 0;
  text-align: right;
}

:deep(.el-dialog__header) {
  margin-right: 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
  padding: 20px;
}

:deep(.el-dialog__body) {
  padding-top: 24px;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid var(--el-border-color-lighter);
  padding: 20px;
}

:deep(.el-button) {
  padding: 8px 20px;
  border-radius: 2px;
}
</style>